package sort;

/**
 * 归并排序
 */
public class MergeSort {
    public void sort(int[] arr) {
        mergeSort(arr, 0, arr.length - 1);
    }

    public void mergeSort(int[] arr, int l, int r) {
        if (l < r) {
            int m = l + (r - l) / 2;
            mergeSort(arr, l, m);
            mergeSort(arr, m + 1, r);
            merge(arr, l, m, r);
        }
    }

    public void merge(int[] arr, int l, int m, int r) {
        int[] L = new int[m - l + 1];
        int[] R = new int[r - m];

        for (int i = 0; i < L.length; i++) {
            L[i] = arr[l + i];
        }
        for (int j = 0; j < R.length; j++) {
            R[j] = arr[m + j + 1];
        }

        int i = 0, j = 0, k = l;

        while (i < L.length && j < R.length) {
            if (L[i] <= R[j]) {
                arr[k++] = L[i++];
            } else {
                arr[k++] = R[j++];
            }
        }

        while (i < L.length) {
            arr[k++] = L[i++];
        }

        while (j < R.length) {
            arr[k++] = R[j++];
        }
    }

    public static void main(String[] args) {
        int[] rank = GenNums.rank(3);
        GenNums.printNums(rank);
        MergeSort mergeSort = new MergeSort();
        mergeSort.sort(rank);
        GenNums.printNums(rank);
        System.out.println(GenNums.check(rank));
    }
}
